<template>
  <div>
    <!--页面区域-->
    <div class="page-view">

      <!--搜索条件表单-->
      <div class="table-operations">
        <a-space>
          <a-form ref="queryForm" :model="data.queryParam" layout="inline">  
            <a-form-item label="字典编码">  
              <a-input v-model:value="data.queryParam.keyCode" placeholder="请输入字典编码" />  
            </a-form-item>  
            <a-form-item label="字典名称">  
              <a-input v-model:value="data.queryParam.keyName" placeholder="请输入字典名称" />  
            </a-form-item>  
            <a-button type="primary" @click="onSearch">搜索</a-button> 
            <a-button type="primary" @click="onReset">重置</a-button> 
          </a-form> 
        </a-space> 
      </div>  

      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">新增</a-button>
          <a-button @click="handleBatchDelete">批量删除</a-button>
        </a-space>
      </div>
      <a-table size="middle" rowKey="id" :loading="data.loading" :columns="columns" :data-source="data.dataList"
        @change="getDataDictionryList" :scroll="{ x: 'max-content' }" :row-selection="rowSelection" :pagination="pagination">
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'role'">
            <span>
              <span v-if="text === '1'">普通用户</span>
              <span v-if="text === '2'">商户</span>
              <span v-if="text === '3'">管理员</span>
            </span>
          </template>
          <template v-if="column.key === 'operation'">
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="showDrawer(record.id)">明细</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="confirmDelete(record)">
                <a href="#">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </div>

    <!--弹窗区域-->
    <!--新增/编辑 数据字典的弹窗-->
    <div>
      <a-modal :visible="modal.visile" :forceRender="true" :title="modal.title" ok-text="确认" cancel-text="取消"
        @cancel="handleCancel" @ok="handleOk">
        <div>
          <a-form ref="myform" :label-col="{ style: { width: '80px' } }" :model="modal.form" :rules="modal.rules">
            <a-row :gutter="24">
              <a-col span="24">
                <a-form-item label="字典编码" name="keyCode">
                  <a-input  :disabled="modal.editFlag" placeholder="请输入" v-model:value="modal.form.keyCode"
                    allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="字典名称" name="keyName">
                 <a-input placeholder="请输入" v-model:value="modal.form.keyName" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="备注" name="remark">
                  <a-textarea
                    v-model:value="modal.form.remark"
                    placeholder="请输入"
                    :auto-size="{ minRows: 2, maxRows: 5 }"
                  />
                </a-form-item>
              </a-col>
              
            </a-row>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>

  <!--编辑 数据字典 明细的右抽屉-->

  <a-drawer width="1040" placement="right" :closable="false" :visible="visible" @close="onClose">
    <p :style="[pStyle, pStyle2]">字典明细列表</p>

    <div class="table-operations">
      <a-space>
        <a-button type="primary" @click="handleAddDictDesc">新增</a-button>
      </a-space>
    </div>
    <!--抽屉里展示table列表-->
    <a-table size="middle" rowKey="id" :loading="data.dictDescLoading" :columns="dictDescColumns" :data-source="data.dictDescList"
         :scroll="{ x: 'max-content' }" :row-selection="rowSelection" :pagination="dictDescPagination">
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'operation'">
            <span>
              <a @click="handleEditDictDesc(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="confirmDeleteDictDesc(record)">
                <a href="#">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>


      <div>
        <a-modal :visible="modal.dictDescVisile" :forceRender="true" :title="modal.title" ok-text="确认" cancel-text="取消"
          @cancel="handleCancelDictDesc" @ok="handleOkDictDesc">
          <div>
            <a-form ref="myform" :label-col="{ style: { width: '100px' } }" :model="modal.formDictDesc" :rules="modal.rules">
              <a-row :gutter="24">
                <a-col span="24">
                  <a-form-item label="明细编码" name="valueCode">
                    <a-input  :disabled="modal.dictDescEditFlag" placeholder="请输入" v-model:value="modal.formDictDesc.valueCode"
                      allowClear />
                  </a-form-item>
                </a-col>
                <a-col span="24">
                  <a-form-item label="明细中文名称" name="valueCn">
                  <a-input placeholder="请输入" v-model:value="modal.formDictDesc.valueCn" allowClear />
                  </a-form-item>
                </a-col>
                <a-col span="24">
                  <a-form-item label="明细英文名称" name="valueEn">
                    <a-input  placeholder="请输入" v-model:value="modal.formDictDesc.valueEn"
                      allowClear />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-modal>
    </div>
   
  </a-drawer>



</template>

<script setup lang="ts">
import { FormInstance, message } from 'ant-design-vue';
import { queryListApi, detailApi, createApi, updateApi, deleteApi, createDictDescApi, updateDictDescApi, deleteDictDescApi } from '/@/api/dataDictionary';
import { getFormatTime } from "/@/utils";


 // 控制页面列表显示的字段
const columns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
  {
    title: '字典编码',
    dataIndex: 'keyCode',
    key: 'keyCode',
    align: 'center',
  },
  {
    title: '字典名称',
    dataIndex: 'keyName',
    key: 'keyName',
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: ({ text }) => getFormatTime(text, true)
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    align: 'center',
    fixed: 'right',
    width: 140,
  },
]);

// 字典明细列表 显示的字段
const dictDescColumns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
  {
    title: '明细编码',
    dataIndex: 'valueCode',
    key: 'valueCode',
    align: 'center',
  },
  {
    title: '明细中文名称',
    dataIndex: 'valueCn',
    key: 'valueCn',
    align: 'center',
  },
  {
    title: '明细英文名称',
    dataIndex: 'valueEn',
    key: 'valueEn',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: ({ text }) => getFormatTime(text, true)
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    align: 'center',
    fixed: 'right',
    width: 140,
  },
]);



// 页面数据
const data = reactive({
  // 字典列表相关的属性
  dataList: [],     
  queryParam: {
    keyword: '',
    pageSize: 10,
    page: 1,
    total: 0,
    keyCode: '',
    keyName: '',
  },
  loading: false,
  selectedRowKeys: [] as any[],

  // 字典明细列表相关的属性
  dictDescList: [], 
  dictDescQueryParam: {
    keyword: '',
    pageSize: 10,
    page: 1,
    total: 0,
  },
  dictDescLoading: false,
  dictDescSelectedRowKeys: [] as any[],
});

// 字典列表分页对象
const pagination = computed(() => ({
  size: 'default',
  current: data.queryParam.page,
  pageSize: data.queryParam.pageSize,
  total: data.queryParam.total,
  onChange: (current) => (data.queryParam.page = current),
  showSizeChanger: false,
  showTotal: (total) => `共${total}条数据`,
}));

// 字典明细列表的分页对象
const dictDescPagination = computed(() => ({
  size: 'default',
  current: data.dictDescQueryParam.page,
  pageSize: data.dictDescQueryParam.pageSize,
  total: data.dictDescQueryParam.total,
  onChange: (current) => (data.dictDescQueryParam.page = current),
  showSizeChanger: false,
  showTotal: (total) => `共${total}条数据`,
}));

// 弹窗数据源
const modal = reactive({
  visile: false,
  dictDescVisile: false,
  editFlag: false,
  dictDescEditFlag: false,
  title: '',
  form: {
    id: undefined,
    keyCode: undefined,
    keyName: undefined,
    remark: undefined
  },
  formDictDesc: {
    id: undefined,
    dictionaryId: undefined,
    valueCode: undefined,
    valueEn: undefined,
    valueCn: undefined
  },
  dictionaryId: undefined,
  rules: {
    keyCode: [{ required: true, message: '请输入', trigger: 'change' }],
    valueCode: [{ required: true, message: '请输入', trigger: 'change' }],
    remark: [{ required: false, message: '请输入', trigger: 'change' }]
  },
});

const myform = ref<FormInstance>();

onMounted(() => {
  getDataDictionryList();
});

// 列表查询——字典主表
const getDataDictionryList = () => {
  data.loading = true;
  queryListApi(data.queryParam)
    .then((res) => {
      data.loading = false;
      data.dataList = res.content.records;
      data.queryParam.total = res.content.total;
      data.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      data.loading = false;
      console.log(err);
    });
};

// 字典详情查询
// 查询字典明细列表
const getDictionryDetail = (dictId: number) => {
  detailApi(dictId)
    .then((res) => {
      data.dictDescLoading = false;
      data.dictDescList = res.content.dictionaryDescList;
      data.dictDescQueryParam.total = res.content.total;
      data.dictDescList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      data.dictDescLoading = false;
      console.log(err);
    });
};


// 搜索按钮调用列表查询接口
const onSearch = () => {
  getDataDictionryList();
};

// 重置搜索条件
const onReset = () => {
  data.queryParam.keyCode = '';
  data.queryParam.keyName = '';
  getDataDictionryList();
};

const rowSelection = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    data.selectedRowKeys = selectedRowKeys;
  },
});

// 新增的方法——字典主表
const handleAdd = () => {
  resetModal();
  modal.visile = true;
  modal.editFlag = false;
  modal.title = '新增';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
};

// 新增的方法——字典明细
const handleAddDictDesc = () => {
  resetModal();
  modal.dictDescVisile = true;
  modal.dictDescEditFlag = false;
  modal.title = '新增';
  // 重置
  for (const key in modal.formDictDesc) {
    modal.formDictDesc[key] = undefined;
  }
};

// 编辑的方法——字典主表
const handleEdit = (record: any) => {
  resetModal();
  modal.visile = true;
  modal.editFlag = true;
  modal.title = '编辑';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  for (const key in record) {
    modal.form[key] = record[key];
  }
};

// 编辑的方法——字典明细
const handleEditDictDesc = (record: any) => {
  resetModal();
  modal.dictDescVisile = true;
  modal.dictDescEditFlag = true;
  modal.title = '编辑';
   // 重置
  for (const key in modal.formDictDesc) {
    modal.formDictDesc[key] = undefined;
  }
  for (const key in record) {
    modal.formDictDesc[key] = record[key];
  }
};

// 删除的方法——字典主表
const confirmDelete = (record: any) => {
  deleteApi({ ids: record.id })
    .then((res) => {
      message.success('删除成功');
      getDataDictionryList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 批量删除的方法——字典主表
const handleBatchDelete = () => {
  console.log(data.selectedRowKeys);
  if (data.selectedRowKeys.length <= 0) {
    message.warn('请勾选删除项');
    return;
  }
  deleteApi({ ids: data.selectedRowKeys.join(',') })
    .then((res) => {
      message.success('删除成功');
      data.selectedRowKeys = [];
      getDataDictionryList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 删除的方法——字典明细
const confirmDeleteDictDesc = (record: any) => {
  deleteDictDescApi(record.id)
    .then((res) => {
      message.success('删除成功');
      getDictionryDetail(modal.dictionaryId);
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 二次确认 点击ok的方法
const handleOk = () => {
  myform.value
    ?.validate()
    .then(() => {
      const formData = new FormData();
      if (modal.form.id) {
        formData.append('id', modal.form.id);
      }
      if (modal.form.keyCode) {
        formData.append('keyCode', modal.form.keyCode);
      }
      if (modal.form.keyName) {
        formData.append('keyName', modal.form.keyName);
      }
      if (modal.form.remark) {
        formData.append('remark', modal.form.remark);
      }
      if (modal.editFlag) {
        updateApi(formData)
          .then((res) => {
            message.success('修改成功');
            hideModal();
            getDataDictionryList();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      } else {
        createApi(formData)
          .then((res) => {
            message.success('添加成功');
            hideModal();
            getDataDictionryList();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      }
    })
    .catch((err) => {
      console.log('不能为空');
    });
};

// 二次确认 点击ok的方法 - 字典明细
const handleOkDictDesc = () => {
  myform.value
    ?.validate()
    .then(() => {
      const formData = new FormData();
      if (modal.formDictDesc.id) {
        formData.append('id', modal.formDictDesc.id);
      }
      formData.append('dictionaryId', modal.dictionaryId);
      if (modal.formDictDesc.valueCode) {
        formData.append('valueCode', modal.formDictDesc.valueCode);
      }
      if (modal.formDictDesc.valueCn) {
        formData.append('valueCn', modal.formDictDesc.valueCn);
      }
      if (modal.formDictDesc.valueEn) {
        formData.append('valueEn', modal.formDictDesc.valueEn);
      }
      if (modal.dictDescEditFlag) {
        updateDictDescApi(formData)
          .then((res) => {
            message.success('修改成功');
            hideModalDictDesc();
            getDictionryDetail(modal.dictionaryId);
          })
          .catch((err) => {
            console.log(err);
            message.warn(err.msg || "操作失败")
          });
      } else {
        createDictDescApi(formData)
          .then((res) => {
            message.success('添加成功');
            hideModalDictDesc();
            getDictionryDetail(modal.dictionaryId);
          })
          .catch((err) => {
            console.log(err);
            message.warn(err.msg || "操作失败")
          });
      }
    })
    .catch((err) => {
      console.log('不能为空');
    });
};

// 二次确认点击取消的方法
const handleCancel = () => {
  hideModal();
};

// 二次确认点击取消的方法- 字典明细
const handleCancelDictDesc = () => {
  hideModalDictDesc();
};

// 恢复表单初始状态
const resetModal = () => {
  myform.value?.resetFields();
};

// 关闭弹窗
const hideModal = () => {
  modal.visile = false;
};

// 关闭弹窗-字典明细
const hideModalDictDesc = () => {
  modal.dictDescVisile = false;
};



const visible = ref<boolean>(false);
const pStyle = {
  fontSize: '16px',
  color: 'rgba(0,0,0,0.85)',
  lineHeight: '24px',
  display: 'block',
  marginBottom: '16px',
};
const pStyle2 = {
  marginBottom: '24px',
};

const showDrawer = (dictId: number) => {
  // 查询字典详情
  getDictionryDetail(dictId);
  modal.dictionaryId = dictId;
  console.log("数据字典ID："+modal.dictionaryId);

  visible.value = true;
};

const onClose = () => {
  visible.value = false;
};


</script>

<style scoped lang="less">
.page-view {
  min-height: 100%;
  background: #fff;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.table-operations {
  margin-bottom: 16px;
  text-align: right;
}

.table-operations>button {
  margin-right: 8px;
}

// 以下class名称是组件生成的，查看页面元素才知道
.ant-form> button {
  margin-right: 8px;
}

</style>
